/*
*ClassName:BaseHttp
*Description:TODO
*Date:2019/5/10 16:37
*/

/**
 * Created by yh on 2018/8/14.
 * http请求
 */

export function baseHttpApi(host, uri, params, method = 'GET', token = '', timeout = 10000) {
    let url = `${host}${uri}`;

    params = params || {};
    let options: any = {
        method,
    };
    // let temp = typeof params === 'string' ? params : querystring.stringify(params);
    let temp = JSON.stringify(params);
    switch (method.toUpperCase()) {
        case 'GET':
            url += '?' + temp;
            // var str = "?";
            // for (var k in params) {
            //     if (str != "?") {
            //         str += "&";
            //     }
            //     str += k + "=" + params[k];
            // }
            // url += encodeURI(str);
            // console.log("Http temp = ",url);
            break;
        case 'POST':
            options.body = temp;
            options.headers = {
                'token': token,
                'Content-Type': 'application/json;charset=UTF-8;',
                // credentials: 'include'
            };
            break;
    }
    console.log('/request uri:', uri, '/post = ', temp);
    return Promise.race([
        fetch(url, options)
            .then((response) => response.text())
            .then((response) => {
                // console.log('fetch ====>', response);
                let data;
                try {
                    data = JSON.parse(response);
                } catch (e) {
                   
                    console.error('response => ', response);
                    console.error('decode json failed.', e.message);
                    return Promise.reject('服务器数据异常!');
                }
                //console.log('data ==>', data);
                if (data.code == 200) {
               
                    console.log('response data => ', uri, data);
                    return data.data;
                } else {
                   
                    console.error('error => ', uri, data);
                    return Promise.reject(new Error(data.message));
                }
            })
            .catch((error) => {
              
                if (error.message == "Failed to fetch" || error.message == "Network request failed") {
                    error.message = "网络请求失败,请重试!";
                }
                throw new Error(error.message);
            }),
        new Promise(function (resolve, reject) {
            setTimeout(() => {
              
                reject(new Error('网络请求超时了,请重试!'))
            }, timeout)
        })]);

    // return fetch(url, options)
    //     .then((response) => response.text())
    //     .then((response) => {
    //         // console.log('fetch ====>', response);
    //         UIMgr.instance.hideLoading();
    //         let data;
    //         try {
    //             data = JSON.parse(response);
    //         } catch (e) {
    //             console.error('response => ', response);
    //             console.error('decode json failed.', e.message);
    //             return Promise.reject('网络状况不佳,请检查你的网络');
    //         }
    //         //console.log('data ==>', data);
    //         if (data.code == 200) {
    //             console.log('response data => ', uri, data);
    //             return data.data;
    //         } else {
    //             console.error('error => ', uri, data);
    //             // let tipStr = ConfigMgr.instance.getCodeConfigMsg(data.code);
    //             // return Promise.reject(tipStr);
    //             return Promise.reject(new Error(data.message));
    //         }
    //     })
    //     .catch((error) => {
    //         UIMgr.instance.hideLoading();
    //         if (error.message == "Failed to fetch" || error.message == "Network request failed") {
    //             error.message = "您的网络不稳定,请重试!";
    //         }
    //         throw new Error(error.message);
    //     });
}

function objEncodeURIString(obj, startStr) {
    let str = startStr;
    Object.keys(obj).map((key) => {
        if (str != startStr) {
            str += "&";
        }
        str += (key) + '=' + (obj[key]);
    });
    return encodeURI(str);
}

export function baseHttpApiWWW(host, uri, params, method = 'GET', token = '', timeout = 10000) {
    let url = `${host}${uri}`;
    let options: any = {
        method,
    };
    params = params || {};
    // let temp = typeof params === 'string' ? params : querystring.stringify(params);
    //let temp = JSON.stringify(params);
    let temp;
    switch (method.toUpperCase()) {
        case 'GET':
            temp = objEncodeURIString(params,"?");
            // var str = "?";
            // for (var k in params) {
            //     if (str != "?") {
            //         str += "&";
            //     }
            //     str += k + "=" + params[k];
            // }
            // url += encodeURI(str);
            // console.log("Http temp = ",url);
            url += '?' + params;
            options.headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
            break;
        case 'POST':
            temp = objEncodeURIString(params,"");
            options.body = temp;
            options.headers = {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
                // credentials: 'include'
            };

            break;
    }
    if (token != '') {
        options.headers.token = token;
    }
    console.log('/request uri:', uri, '/post = ', temp, "/token", token);
    return Promise.race([
        fetch(url, options)
            .then((response) => response.text())
            .then((response) => {
                // console.log('fetch ====>', response);

                let data;
                try {
                    data = JSON.parse(response);
                } catch (e) {
                    console.error('response => ', response);
                    console.error('decode json failed.', e.message);
                  
                    return Promise.reject('服务器数据异常!');
                }
                //console.log('data ==>', data);
                if (data.code == 200) {
                    console.log('response data => ', uri, data);
                   
                    return data.data;
                } else {
                  
                    console.error('error => ', uri, data);
                    // let tipStr = ConfigMgr.instance.getCodeConfigMsg(data.code);
                    // return Promise.reject(tipStr);
                    return Promise.reject(new Error(data.message));
                }
            })
            .catch((error) => {
              
                if (error.message == "Failed to fetch" || error.message == "Network request failed") {
                    error.message = "网络请求失败,请重试!";
                }
                throw new Error(error.message);
            }),
        new Promise(function (resolve, reject) {
            setTimeout(() => {
               
                reject(new Error('网络请求超时了,请重试!'))
            }, timeout)
        })]);
}
